Namespace IO

  ''' <summary>
  ''' General path helper methods.
  ''' </summary>
  ''' <remarks></remarks>
  Public NotInheritable Class PathHelper

    ''' <summary>
    ''' Converts a long path name into a short path name.
    ''' </summary>
    ''' <param name="longPathName">Long path name to convert.</param>
    ''' <returns>Short path name.</returns>
    ''' <remarks></remarks>
    Public Shared Function ConvertLongPathToShort(ByVal longPathName As String) As String

      If String.IsNullOrEmpty(longPathName) Then
        Throw New ArgumentNullException("longPathName")
      End If

      Dim shortNameBuffer As New System.Text.StringBuilder
      Dim size As Integer = UnsafeNativeMethods.GetShortPathName(longPathName, shortNameBuffer, shortNameBuffer.Capacity)

      If (size >= shortNameBuffer.Capacity) Then
        shortNameBuffer.Capacity = size + 1
        If UnsafeNativeMethods.GetShortPathName(longPathName, shortNameBuffer, shortNameBuffer.Capacity) = 0 Then
          shortNameBuffer.Remove(0, shortNameBuffer.Length)
        End If
      End If

      Return shortNameBuffer.ToString()

    End Function

    ''' <summary>
    ''' Finds a path on the computer. Checks all local drives only.
    ''' </summary>
    ''' <param name="path">Path to find, can include file name.</param>
    ''' <returns>First path found.</returns>
    ''' <remarks></remarks>
    Public Shared Function FindPathOnDrives(ByVal path As String) As String

      Dim tempPath As String = String.Empty

      If Not IO.FileHelper.FileExists(System.IO.Path.GetFullPath(path)) Then
        Dim pathRoot As String
        Dim tempDrive As System.IO.DriveInfo
        Dim testPath As String
        pathRoot = System.IO.Path.GetPathRoot(path)

        'Search all local drives for the path/file
        For Each tempDrive In dotNetTips.Utility.ComputerHelper.ComputerReadyDrives

          If tempDrive.IsReady Then

            testPath = Replace(path, pathRoot, tempDrive.Name)
            If IO.FileHelper.FileExists(testPath) Then
              tempPath = testPath
              Exit For
            End If

          End If
        Next

      Else

        tempPath = path

      End If

      Return tempPath

    End Function

    Private Sub New()
    End Sub
  End Class

End Namespace
